package org.concepts.java.antlr.calculator;

import org.antlr.runtime.ANTLRStringStream;
import org.antlr.runtime.CommonTokenStream;
import org.antlr.runtime.RecognitionException;
import org.antlr.runtime.tree.CommonTree;
import org.antlr.runtime.tree.CommonTreeNodeStream;

/**
 * Simple calculator to showcase the utility of building Abstract syntax tree
 * (AST) in the parser and then processing it using a tree walker.
 * <p/>
 * 
 * 
 * 
 */
public class Calculator {

  public static int calculate(String input) {
    try {
      CommonTree tree = (CommonTree) new CalculatorParser(
          new CommonTokenStream(new CalculatorLexer(
              new ANTLRStringStream(input)))).expr().getTree();
      
      System.out.println("\n\nInput : " + input + "\n" + "AST text : "
          + tree.getText() + "\n" + "AST tree : " + tree.toStringTree());
      
      CalculatorWalker walker = new CalculatorWalker(new CommonTreeNodeStream(
          tree));
      int result = walker.expr();
      System.out.println("result : " + result);
      return result;
      
    } catch (RecognitionException e) {
      e.printStackTrace();
      throw new RuntimeException(e.getMessage(), e);
    }
  }

}
